//
//  AccountregistrationVController.m
//  MyChatchat
//
//  Created by lanou3g on 16/3/31.
//  Copyright © 2016年 小灰灰. All rights reserved.
//

#import "AccountregistrationVController.h"
#import "PrefixHeader.pch"

#define LXdistance 50
#define LWdistance LXdistance * 2
#define LhInputboxdistance 70

@interface AccountregistrationVController ()<UITextFieldDelegate>

@end

@implementation AccountregistrationVController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"账号注册";
    
    //***** 布局账号注册界面 *****//
    [self layoutAccountregistration];
    
    [self layoutButton];
    
    
}

//***** 布局返回按钮 *****//
- (void)layoutButton{
    //*** 返回按钮 ***//
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStyleDone) target:self action:@selector(leftAction)];
}
//***** 返回按钮  *****//
- (void)leftAction{
    if ((self.account.text == nil || [self.account.text isEqualToString:@""]) && (self.password.text == nil || [self.password.text isEqualToString:@""]) && (self.Confirmpassword.text == nil || [self.Confirmpassword.text isEqualToString:@""]))
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定返回吗! ! !" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }];
        UIAlertAction *abolish = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cencel];
        [alert addAction:abolish];
        
    }
}

//***** 布局账号注册界面 *****//
- (void)layoutAccountregistration
{    
    //***** 手机号输入框 *****//
    UIView *aView = [[UIView alloc]init];
    aView.frame = CGRectMake(LXdistance, KCGFloatheight / 5 + 5, KCGFloatwidth - LWdistance, 1);
    aView.backgroundColor = [UIColor redColor];
    [self.view addSubview:aView];
    
    self.account = [[UITextField alloc]init];
    self.account.frame = CGRectMake(LXdistance, KCGFloatheight / 5 - 20, KCGFloatwidth - LWdistance, 30);
    self.account.placeholder = @"请输入账号";
    self.account.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.account.delegate = self;
    [self.view addSubview:self.account];
    
    self.aLabel = [[UILabel alloc] init];
    self.aLabel.frame = CGRectMake(LXdistance, KCGFloatheight / 5 + 7, KCGFloatwidth - LWdistance, 15);
    self.aLabel.text = @"请输入以字母开头的7-11位用户名";
    self.aLabel.font = [UIFont systemFontOfSize:13];
    self.aLabel.textColor = [UIColor redColor];
    [self.view addSubview:self.aLabel];
    
    
    
    
    //***** 密码输入框 *****//
    UIView *bView = [[UIView alloc]init];
    bView.frame = CGRectMake(LXdistance, KCGFloatheight / 5 * 2 - LhInputboxdistance + 5, KCGFloatwidth - LWdistance, 1);
    bView.backgroundColor = [UIColor redColor];
    [self.view addSubview:bView];
    
    self.password = [[UITextField alloc]init];
    self.password.frame = CGRectMake(LXdistance, KCGFloatheight / 5 * 2 - LhInputboxdistance - 20, KCGFloatwidth - LWdistance, 30);
    self.password.delegate = self;
    self.password.secureTextEntry = YES;
    self.password.placeholder = @"请输入密码";
    [self.view addSubview:self.password];
    
    
    
    
    //***** 确认密码输入框 *****//
    UIView * cView = [[UIView alloc] init];
    cView.frame = CGRectMake(LXdistance, KCGFloatheight / 5 * 3 - LhInputboxdistance * 2 + 5, KCGFloatwidth - LWdistance, 1);
    cView.backgroundColor = [UIColor redColor];
    [self.view addSubview:cView];
    
    self.Confirmpassword = [[UITextField alloc] init];
    self.Confirmpassword.frame = CGRectMake(LXdistance, KCGFloatheight / 5 * 3 - LhInputboxdistance * 2 - 20, KCGFloatwidth - LWdistance, 30);
    self.Confirmpassword.delegate = self;
    self.Confirmpassword.secureTextEntry = YES;
    self.Confirmpassword.placeholder = @"请再次输入密码";
    [self.view addSubview:self.Confirmpassword];
    
    
    //***** 注册按钮 *****//
    self.Signupbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.Signupbutton.frame = CGRectMake(KCGFloatwidth / 2 - 75, KCGFloatheight / 5 * 4 - LhInputboxdistance * 3 - 20, 150, 40);
    self.Signupbutton.backgroundColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:0.65];
    self.Signupbutton.layer.cornerRadius = 5;
    [self.Signupbutton addTarget:self action:@selector(SignupbuttonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.Signupbutton setTitle:@"注册" forState:(UIControlStateNormal)];
    [self.view addSubview:self.Signupbutton];
    
}

- (void)SignupbuttonAction
{
    
    NSString *account = self.account.text;
    NSString *password = self.password.text;
    NSString *Confirmpassword = self.Confirmpassword.text;
    
    NSString *userNameRegex = @"^[a-z][A-Za-z0-9]{6,11}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    if (account.length != 0)
    {
        self.Signupbutton.userInteractionEnabled = NO;
        [self.Signupbutton setTitle:@"正在注册..." forState:(UIControlStateNormal)];

        
        if ([userNamePredicate evaluateWithObject:self.account.text])
        {
            if (password.length != 0)
            {
                if (Confirmpassword.length != 0)
                {
                    if ([self.password.text isEqualToString:self.Confirmpassword.text] && password.length == Confirmpassword.length)
                    {
                        AVUser *user = [AVUser user];// 新建 AVUser 对象实例
                        user.username = self.account.text;// 设置用户名
                        user.password =  self.Confirmpassword.text;// 设置密码
                        
                        self.account.userInteractionEnabled = NO;
                        self.password.userInteractionEnabled = NO;
                        self.Confirmpassword.userInteractionEnabled = NO;
                        
                        [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                            
                            if (succeeded)
                            {
                                self.alertController = [UIAlertController alertControllerWithTitle:@"恭喜注册成功" message:@"(3秒之后自动返回)" preferredStyle:UIAlertControllerStyleAlert];
                                [self presentViewController:self.alertController animated:YES completion:^{
                                    __block int timeout= 2; //倒计时时间
                                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                                    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                                    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                                    dispatch_source_set_event_handler(_timer, ^{
                                        if(timeout<=0){ //倒计时结束，关闭
                                            dispatch_source_cancel(_timer);
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                //*** 返回提示框 ***//
                                                [self dismissViewControllerAnimated:YES completion:nil];
                                                //*** 返回上一个界面 ***//
                                                [self dismissViewControllerAnimated:YES completion:nil];
                                            });
                                        }else{
                                            int seconds = timeout % 3;
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                //设置界面的按钮显示 根据自己需求设置
                                                self.alertController.message = [NSString stringWithFormat:@"(%d秒之后自动返回)",seconds];
                                            });
                                            timeout--;
                                        }
                                    });
                                    dispatch_resume(_timer);
                                }];
                                
                            }
                            else
                            {
                                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"用户名已经存在" preferredStyle:UIAlertControllerStyleAlert];
                                
                                [self presentViewController:alert animated:YES completion:^{
                                    
                                }];
                                UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                                    
                                    self.Signupbutton.userInteractionEnabled = YES;
                                    [self.Signupbutton setTitle:@"注册" forState:(UIControlStateNormal)];

                                    
                                    self.account.userInteractionEnabled = YES;
                                    self.password.userInteractionEnabled = YES;
                                    self.Confirmpassword.userInteractionEnabled = YES;
                                    
                                }];
                                
                                [alert addAction:cencel];
                            }
                        }];
                    }
                    else
                    {
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"两次密码不相同" preferredStyle:UIAlertControllerStyleAlert];
                        
                        [self presentViewController:alert animated:YES completion:^{
                            
                        }];
                        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                            
                            self.Signupbutton.userInteractionEnabled = YES;
                            [self.Signupbutton setTitle:@"注册" forState:(UIControlStateNormal)];
                        }];
                        
                        [alert addAction:cencel];
                        
                    }
                }
                else
                {
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认密码不能为空" preferredStyle:UIAlertControllerStyleAlert];
                    
                    [self presentViewController:alert animated:YES completion:^{
                        
                    }];
                    UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                        
                        
                    }];
                    
                    [alert addAction:cencel];
                }
            }
            else
            {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"密码不能为空" preferredStyle:UIAlertControllerStyleAlert];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                    
                    
                }];
                
                [alert addAction:cencel];
            }

        }
        else
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"用户名输入不正确" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:alert animated:YES completion:^{
                
            }];
            UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                
                self.Signupbutton.userInteractionEnabled = YES;
                [self.Signupbutton setTitle:@"注册" forState:(UIControlStateNormal)];
            }];
            
            [alert addAction:cencel];
        }
        
    }
    else
    {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"账号不能为空" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        [alert addAction:cencel];
    }

    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    [userNamePredicate evaluateWithObject:name];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
